<template>
    <div class="views">
        <h3 class="title">
            <span>流程编辑</span>
            <span class="time"></span>
        </h3>

        <div class="wapper" >
            <div class="views-tree tree-container" @dragend="savewfList()">
                <el-tree ref="treeData"
                    :data="treeData"
                    node-key="id"
                    lazy
                    :load="loadNode"
                    :default-expanded-keys="[1, 2, 3]"
                    :default-checked-keys="[1]"
                    :props="defaultProps"
                    :expand-on-click-node="false"
                    @node-click="nodeClick"
                    draggable
                    :allow-drop="allowDrop"
                    @node-drop="handleDrop"
                >
                    <span class="custom-tree-node" slot-scope="{ node,data }">
                        <span>
                            <i :class="node.icon"></i>
                            {{ node.data.name }}
                        </span>
                        <span>
                            <el-button type="text" icon="el-icon-plus" @click="addtree(node)"></el-button>
                            <el-button type="text" icon="el-icon-edit" @click="edittree(node)"></el-button>
                            <el-button type="text" icon="el-icon-delete" @click="deltree(node)"></el-button>
                        </span>
                    </span>
                </el-tree>
            </div>
            <div class="info">
                <div class="top-menu"  @dragend="saveActionList()">
                    <draggable v-model="menuList" :options="dragOptions">
                    <transition-group tag="div" id="menuList" class="clearFix">
                    <div
                        class="item"
                        :key="item.id"
                        :class="{'act': mAct == item.id}"
                        v-for="(item, index) in menuList"
                        @click="itemClick(item)"
                    >
                        <div :class="item.icon"></div>
                        <p class="text">{{item.actionname}}</p>
                        <span v-if="mAct == item.id">
                            <el-button type="text" icon="el-icon-edit" @click="editaction(item)"></el-button>
                            <el-button type="text" icon="el-icon-delete" @click="delaction(item)"></el-button>
                        </span>
                    </div>
                        </transition-group>
                    </draggable>
                    <div v-if="showAddAction" class="item" @click="addActionClick()" >
                        <div class='add'></div>
                    </div>
                </div>
                <div class="view-wrapper">
                    <div class="triangle"></div>
                    <div class="unusual" v-if="mAct > 0">
                        <vServEdit :actionid='actionid'></vServEdit>
                    </div>
                </div>
            </div>

            <!-- 流程节点编辑弹出框 -->
            <el-dialog title="编辑" :visible.sync="editWFVisible" width="30%" :close-on-click-modal="false">
                <el-form ref="wfform" v-model="wfform" label-width="70px">
                    <el-form-item label="节点名">
                        <el-input v-model="wfform.id" v-if="false"></el-input>
                        <el-input v-model="wfform.parId" v-if="false"></el-input>
                        <el-input v-model="wfform.name" @input="change($event)"></el-input>
                    </el-form-item>
                    <el-form-item label="关联流程ID(无则不填)">
                        <el-input v-model="wfform.code" @input="change($event)" :disabled="wfform.id != undefined"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editWFVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveWFEdit">确 定</el-button>
                </span>
            </el-dialog>
            <!--end 流程节点编辑弹出框 -->

            <!-- 环节编辑弹出框 -->
            <el-dialog title="编辑" :visible.sync="editVisible" width="70%" :close-on-click-modal="false">
                <el-form ref="form" :model="form" label-width="70px">
                    <el-form-item label="环节ID">
                        <el-input v-model="form.id" v-if="false"></el-input>
                        <el-input v-model="form.scaid" v-if="false"></el-input>
                        <el-input v-model="form.seq" v-if="false"></el-input>
                        <el-input v-model="form.icon" v-if="false"></el-input>
                        <el-input v-model="form.actionid" @input="change($event)" :disabled="form.id != undefined"></el-input>
                    </el-form-item>
                    <el-form-item label="环节名">
                        <el-input v-model="form.actionname" @input="change($event)"></el-input>
                    </el-form-item>
                    <el-form-item label="环节图标">
                        <div class="circle">
                          <ul class="circle-ul">
                            <li v-for="(item) of iconList" :key="item.id" class="circle-li">
                              <div v-on:click="changeAList(item.id)" v-bind:class="{changeBorder:item.id==a}">
                                <img :src="item.coverImg" style="width: 55px;height: 55px;padding-top: 5px;" alt />
                                <div v-if="item.id==a" class="topic-shade2">
                                  <div class="shade2"><img src="@/assets/img/checked.gif" style="width: 21px;height: 21px;" alt /></div>
                                </div>
                              </div>
                            </li>
                          </ul>
                        </div>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
            </el-dialog>
            <!--end 环节编辑弹出框 -->
        </div>
    </div>
</template>

<script>
import vServEdit from './ServEdit.vue';
import draggable from 'vuedraggable';
import wfApi from '@/api/workflow';

export default {
    data() {
        return {
            dragOptions:{
                animation: 120,
                scroll: true,
                group: 'sortlist',
                ghostClass: 'ghost-style'
            },
            treeData: [],
            defaultProps: {
                children: 'children',
                label: 'label',
                isLeaf: 'isLeaf'
            },
            menuList: [],
            mAct: 0,
            scaid: '',
            showAddAction: false,
            editVisible: false,
            editWFVisible: false,
            form: {},
            wfform: {},
            checkedtreeId: 0,
            actionid:'',
            a:true,
                  iconList: [
                    {
                      id: "m1",
                      coverImg:require('@/assets/img/m1.png')
                    },
                    {
                      id: "m2",
                      coverImg:require('@/assets/img/m2.png')
                    },
                    {
                      id: "m3",
                      coverImg:require('@/assets/img/m3.png')
                    },
                    {
                      id: "m4",
                      coverImg:require('@/assets/img/m4.png')
                    },
                    {
                      id: "m5",
                      coverImg:require('@/assets/img/m5.png')
                    },
                    {
                      id: "m6",
                      coverImg:require('@/assets/img/m6.png')
                    },
                    {
                      id: "m7",
                      coverImg:require('@/assets/img/m7.png')
                    },
                    {
                      id: "m8",
                      coverImg:require('@/assets/img/m8.png')
                    },
                     {
                       id: "m9",
                       coverImg:require('@/assets/img/m9.png')
                     }
                  ]
        };
    },
    components: {
        vServEdit,
        draggable
    },
    methods: {
        changeAList(id){
            this.form.icon = id;
            console.log('icon='+id);

              if(this.a == id){
                  this.a =! this.a;
              }else{
                  this.a =id;
              }
            },

        change(e){
            this.$forceUpdate();
        },
        //加载流程树
         loadNode(node, resolve) {
            let parId = node.level === 0 ? 0 : node.data.id;

            console.log('loadNode,parId='+parId);

            if (node.data.haschildren == 0) {
                return resolve([]);
            }
            wfApi.loadtreeForEdit(parId).then(res => {
                res.list.forEach(item => {
                    item.isLeaf = (item.haschildren == '0' ? true : false);
                })
                resolve(res.list);
            });
        },

        //只允许同级拖拽
        allowDrop(draggingNode, dropNode, type){
            if(draggingNode.level === dropNode.level){
                if(draggingNode.parent.id === dropNode.parent.id){
                    return type === 'prev'
                }
            }else{
                // 不同级进行处理
            }
        },

        //拖拽成功完成时触发的事件，在这里可以将节点拖拽后的顺序返给后端
        handleDrop(node,data,type,event){
            let arr=[];

            //data为拖拽后节点信息，找到它的父级，在从父级找子集
            let child = data.parent.childNodes;
            for(var key in child){
                arr.push(child[key].data);
            }
            //转为JSON字符串发请求带走信息
            //idSort(JSON.stringify(arr))
            console.log(JSON.stringify(arr));

            wfApi.saveWfList(arr).then(res => {
                if (res.code == 0){
                  this.$message.success('保存成功');
                    data.parent.loaded = false;
                    data.parent.expand();
                }else{
                  this.$message.error(res.msg);
                }
            })
        },

        nodeClick(data, checked, node) {
            this.checkedtreeId = data.id;

            this.loadAction(data.code);

            console.log(`点击流程节点：${data.id} ${data.code} ${this.actionid}`);
            if (data.code == null){
                this.showAddAction = false;
            }else{
                this.showAddAction = true;
            }

            // this.$refs.treeForm.setCheckedNodes([data]);
        },

        loadAction(scaid){
            this.scaid = scaid;
            this.actionid = '';
            this.mAct = '';

            if (scaid != ''){
                wfApi.loadActionWithoutTotal(scaid).then(res => {
                   this.menuList = res.list;
                 })
            }else{
                this.menuList = [];
            }
        },

        addtree(node) {
            console.log(`新增流程节点：${node.data.parId}`);
            // 清空之前的数据
            this.wfform = {};
            this.wfform.parId = node.data.parId;
            this.wfform.lvlId = node.data.id;
            this.editWFVisible = true;
        },
        edittree(node) {
           console.log(`编辑流程节点：${node.data.id}`);
            this.wfform.lvlId = node.data.id;
           this.wfform.id = node.data.id;
           this.wfform.parId = node.data.parId;
           this.wfform.name = node.data.name;
           this.wfform.code = node.data.code;
            this.wfform.seq = node.data.seq;
           this.editWFVisible = true;
        },
        deltree(node) {
           console.log(`删除流程节点：${node.data.id} ${node.data.name}`);
           wfApi.delWftree(node.data.id).then(res => {
                if (res.code == 0){
                  this.$message.success('删除成功');

                  //重新加载本流程
                  node.parent.loaded = false;
                  node.parent.expand();
                }else{
                  this.$message.error(res.msg);
                }
              })
        },
        savewfList(){
            console.log(this.treeData);
        },

        itemClick(item) {
            this.mAct = item.id;
            this.actionid = item.actionid;
            console.log(`点击环节：${item.id} ${this.actionid}`);
        },

        saveActionList(){
            console.log(this.menuList);
            wfApi.saveActionList(this.menuList).then(res => {
                if (res.code == 0){
                  this.$message.success('保存成功');

                }else{
                  this.$message.error(res.msg);
                }
            })
        },

        editaction(node) {
           console.log(`编辑环节：${node.id} ${node.actionid} ${node.actionname}`);
           this.form.id = node.id;
           this.form.scaid = node.scaid;
           this.form.seq = node.seq;
           this.form.actionid = node.actionid;
           this.form.actionname = node.actionname;
           this.form.icon = node.icon;
           this.changeAList(node.icon);
           this.editVisible = true;
        },

        delaction(node) {
           console.log(`删除环节：${node.id} ${node.name}`);
           wfApi.delWf(node.id).then(res => {
                if (res.code == 0){
                  this.$message.success('删除成功');
                  //刷新
                  this.loadAction(this.scaid);
                }else{
                  this.$message.error(res.msg);
                }
           })
        },

        addActionClick() {
            console.log('新增环节，scaid='+this.scaid);
            this.form = {};
            this.form.scaid = this.scaid;
            this.form.actionid = this.scaid+'_';
            this.editVisible = true;
        },

        //保存流程树（编辑或新增操作）
        saveWFEdit(){
            wfApi.saveWf(this.wfform).then(res => {
                 if (res.code == 0){
                     this.$message.success('保存成功');
                     this.editWFVisible = false;
                     let parentNode = this.$refs.treeData.getNode(this.wfform.parId);
                     if (parentNode == undefined) {
                         // 新增和编辑时保存了同级节点的id
                         parentNode = this.$refs.treeData.getNode(this.wfform.lvlId).parent;
                     }
                     parentNode.loaded = false;
                     parentNode.expand();
                 }else{
                     this.$message.error(res.msg);
                 }
            })
        },
        // 保存环节编辑
        saveEdit() {
            console.log(` 保存 ${this.scaid} 环节`);
            //this.form.scaid = this.scaid;
            console.log(JSON.stringify(this.form));
            wfApi.saveAction(this.form).then(res => {
                 if (res.code == 0){
                     this.$message.success('保存成功');
                     this.editVisible = false;
                     this.loadAction(this.scaid);
                 }else{
                     this.$message.error(res.msg);
                 }
               })
        }
    }
};
</script>

<style scoped>
.el-tree {
    margin-top: 20px;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}

.views .title {
    height: 50px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #d4d4d4;
    font-size: 16px;
    font-weight: bold;
    padding: 0 20px;
    color: #333;
}
.views .time {
    flex: 1;
    text-align: right;
}
.wapper {
    display: flex;
    margin: 20px;
    position: relative;
}
.wapper .views-tree {
    width: 250px;
    overflow-y: hidden !important;
    height: 100%;
}

/* /deep/ .el-checkbox__input.is-checked .el-checkbox__inner,
/deep/ .el-checkbox__input.is-indeterminate .el-checkbox__inner {
    background-color: #ed795a;
    border-color: #ed795a;
} */

/* 树形结构节点添加连线 */
.tree /deep/ .el-tree-node {
    position: relative;
    padding-left: 16px;
}

.tree /deep/ .el-tree-node__children {
    padding-left: 16px;
}

.tree /deep/ .el-tree-node :last-child:before {
    height: 38px;
}

.tree /deep/ .el-tree > .el-tree-node:before {
    border-left: none;
}

.tree-container /deep/ .el-tree > .el-tree-node:after {
    border-top: none;
}

.tree /deep/ .el-tree-node:before {
    content: '';
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
}

.tree /deep/ .el-tree-node:after {
    content: '';
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
}
.tree /deep/ .el-tree-node__expand-icon.is-leaf {
    display: none;
}

.tree /deep/ .el-tree-node:before {
    border-left: 1px solid #c7c7c7;
    bottom: 0px;
    height: 100%;
    top: -26px;
    width: 1px;
}

.tree /deep/ .el-tree-node:after {
    border-top: 1px solid #c7c7c7;
    height: 20px;
    top: 12px;
    width: 24px;
}

.wapper .info {
    width: 100%;
}
.top-menu {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.top-menu .item {
    padding-top: 13px;
    width: 75px;
    height: 62px;
    font-size: 12px;
    text-align: center;
    border-radius: 5px;
    background-color: #f7f9fd;
    cursor: pointer;
    position: relative;
    float: left;
    margin-right: 20px;
}
.top-menu .item .nums {
    position: absolute;
    top: -6px;
    right: -15px;
    border: 1px solid #fff;
    border-radius: 15px;
    color: #fff;
    width: 25px;
    height: 15px;
    line-height: 17px;
    font-size: 12px;
    padding-left: 10px;
    background: url(../../../assets/img/attention-fff.png) 3px 50% no-repeat #ed795a;
    background-size: 13px;
}
.top-menu .item .m1 {
    width: 20px;
    height: 25px;
    margin: 0 auto;
    background: url(../../../assets/img/m1.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item .m2 {
    width: 20px;
    height: 25px;
    margin: 0 auto;
    background: url(../../../assets/img/m2.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item .m3 {
    width: 20px;
    height: 25px;
    margin: 0 auto;
    background: url(../../../assets/img/m3.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item .m4 {
    width: 20px;
    height: 25px;
    margin: 0 auto;
    background: url(../../../assets/img/m4.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item .m5 {
    width: 20px;
    height: 25px;
    margin: 0 auto;
    background: url(../../../assets/img/m5.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item .m6 {
    width: 20px;
    height: 25px;
    margin: 0 auto;
    background: url(../../../assets/img/m6.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item .m7 {
    width: 20px;
    height: 25px;
    margin: 0 auto;
    background: url(../../../assets/img/m7.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item .m8 {
    width: 20px;
    height: 25px;
    margin: 0 auto;
    background: url(../../../assets/img/m8.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item .m9 {
    width: 20px;
    height: 25px;
    margin: 0 auto;
    background: url(../../../assets/img/m9.png) 0 0 no-repeat;
    background-size: contain;
}

.top-menu .item .add {
    width: 30px;
    height: 40px;
    margin: 0 auto;
    background: url(../../../assets/img/Add.png) 0 0 no-repeat;
    background-size: contain;
}

.top-menu .act {
    background-color: #ed795a;
}
.top-menu .item .text {
    margin-top: 12px;
}
.top-menu .act .text {
    color: #fff;
}
.top-menu .item.act .m1 {
    background: url(../../../assets/img/m1-fff.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item.act .m2 {
    background: url(../../../assets/img/m2-fff.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item.act .m3 {
    background: url(../../../assets/img/m3-fff.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item.act .m4 {
    background: url(../../../assets/img/m4-fff.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item.act .m5 {
    background: url(../../../assets/img/m5-fff.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item.act .m6 {
    background: url(../../../assets/img/m6-fff.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item.act .m7 {
    background: url(../../../assets/img/m7-fff.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item.act .m8 {
    background: url(../../../assets/img/m8-fff.png) 0 0 no-repeat;
    background-size: contain;
}
.top-menu .item.act .m9 {
    background: url(../../../assets/img/m9-fff.png) 0 0 no-repeat;
    background-size: contain;
}

.view-wrapper {
    border: 1px solid #fce8e3;
    margin-top: 20px;
    position: relative;
}
.view-wrapper .triangle {
    width: 15px;
    height: 9px;
    position: absolute;
    top: -9px;
    left: 30px;
    background: url(../../../assets/img/arrow.png) 0 0 no-repeat #fff;
    background-size: contain;
}
.unusual {
    padding: 20px 10px;
}
.check {
    background-color: #fffdfc;
}

.circle{
  position: relative;
  width: 700px;
  left: 15px;
}
.circle-ul {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  width: 700px;
  padding: 0;
  margin: 14px 0 0 50px;
}

.circle-li {
  margin-right: 20px;
  list-style: none;
  margin-bottom: 20px;
}

.topic-shade {
  display: none;
}

.changeBorder {
  width: 77px;
  height: 77px;
  position: relative;
  cursor: pointer;
  border: 1px dashed #969696;
  margin: -1px -8px 0 -8px;
}

  .topic-shade2 {
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    position: absolute;
    top: 66px;
    right: 0;
    bottom: 0;
    left: 65px;
}
    .shade2 {
      margin-bottom: 4px;
      }
</style>